/**
 * Copyright (C) 2011 GreenSoft S.A.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *        http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ar.com.greensoft.neosystem.dao.jpa;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;

import ar.com.greensoft.neosystem.dao.PaisDao;
import ar.com.greensoft.neosystem.dao.ProvinciaDao;
import ar.com.greensoft.neosystem.model.address.Pais;
import ar.com.greensoft.neosystem.model.address.Pais_;
import ar.com.greensoft.neosystem.model.address.Provincia;
import ar.com.greensoft.neosystem.model.address.Provincia_;
import ar.com.greensoft.neosystem.model.references.ISO3166_1;
import ar.com.greensoft.neosystem.search.SearchFilter;
import ar.com.greensoft.neosystem.search.address.ProvinciaSearchFilter;
import ar.com.greensoft.neosystem.util.SearchUtil;

/**
 * Java Persistence API Implementation of Provincia Data Access Object Pattern
 * @author Jorge E. Villaverde
 * @date 04/10/2011
 * @version 1.1
 */
@Stateless
public class JpaProvinciaDaoImpl 
	extends AbstractLongIdJpaDaoImpl<Provincia> 
	implements ProvinciaDao{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@EJB
	private PaisDao paisDao;
	
	@Override
	protected Class<Provincia> getEntityClazz() {
		return Provincia.class;
	}

	@Override
	protected String getFindByNameNamedQuery() {
		return Provincia.FIND_BY_NAME_QUERY_NAME;
	}

	@Override
	public List<Provincia> findLikeName(String name) {
		logger.trace("Returning the list of " + getEntityClazz().getSimpleName() + " with name like: " + name);
		
		TypedQuery<Provincia> query = 
				getEntityManager().createNamedQuery(Provincia.FIND_LIKE_NAME_QUERY_NAME, Provincia.class);

		query.setParameter("name", name);

		return query.getResultList();
	}

	@Override
	protected Expression<Boolean> createWhereFromSearchFilter(SearchFilter searchFilter, Root<Provincia> root) {
		if(searchFilter == null || !searchFilter.hasFilter())
			return null;
		
		ProvinciaSearchFilter psf = (ProvinciaSearchFilter)searchFilter;
		Predicate predicate = null;
		CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
		
		if(psf.getPais() != null){
			Predicate predicatePais = builder.equal(
					root.get(Provincia_.pais),
					psf.getPais());
			predicate = appendAndPredicate(predicate, predicatePais);
		}
		if(!StringUtils.isBlank(psf.getNombre())){
			String searchText = SearchUtil.likeString(psf.getNombre());
			Predicate predicateNombre = builder.like(
					root.get(Provincia_.name),
					searchText);
			predicate = appendAndPredicate(predicate, predicateNombre);
		}
		return predicate;
	}

	protected List<Order> createOrders(Root<Provincia> root){
		List<Order> ret = new ArrayList<Order>();
		Join<Provincia, Pais> joinPais = root.join(Provincia_.pais);
		CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
		ret.add(builder.asc(joinPais.get(Pais_.name)));
		ret.add(builder.asc(root.get(Provincia_.name)));
		return ret;
	}
	
	@Override
	public List<Provincia> findByPais(Pais pais) {
		if(pais == null)
			throw new IllegalArgumentException("Pais is null");
		
		logger.trace("Returning the list of " + getEntityClazz().getSimpleName() + " with pais = " + pais.getName());
		
		TypedQuery<Provincia> query = 
				getEntityManager().createNamedQuery(Provincia.FIND_BY_PAIS, Provincia.class);

		query.setParameter("pais", pais);

		return query.getResultList();
	}

	@Override
	public List<Provincia> findByPais(ISO3166_1 codigoISO) {
		Pais pais = paisDao.findByCode(codigoISO);
		return findByPais(pais);
	}

	@Override
	public Provincia findByName(String name) {
		logger.trace("Returning the " + getEntityClazz().getSimpleName() + " with name like: " + name);
		
		TypedQuery<Provincia> query = getEntityManager().createNamedQuery(
				Provincia.FIND_BY_NAME_QUERY_NAME, Provincia.class);

		query.setParameter("name", name);

		return findSingleResult(query);
	}

	@Override
	public Provincia findByPaisName(Pais pais, String name) {
		if(pais == null)
			throw new IllegalArgumentException("Pais is null");
		
		logger.trace("Returning the list of " + getEntityClazz().getSimpleName() + " with Provincia = " + pais.getName());
		
		TypedQuery<Provincia> query = 
				getEntityManager().createNamedQuery(
						Provincia.FIND_BY_PAIS_NAME_QUERY_NAME, 
						Provincia.class);

		query.setParameter("pais", pais);
		query.setParameter("name", name);

		return findSingleResult(query);
	}
}